﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace AutoChess
{
    public class HeroJumpState : Yunchang.FsmStateBase<HeroBehaviourState>
    {
        private JumpType jumpType;
        private Vector3 targetPos;
        private Vector3 startPos;
        private Action endCall;
        private string animName = AniName.RUSH;
        private Transform heroActor;

        private CommonAnimCurve commonCurve;

        private float animPlayTime = 1;
        private float _elapseTime = 0;
        HeroBehaviourCtr ctr;
        public HeroJumpState(HeroBehaviourState stateType, HeroBehaviourCtr controller) : base(stateType, controller)
        {
            ctr = controller;
        }
        public override void Enter()
        {
            _elapseTime = 0;
            heroActor = ctr.heroRenderer.transform;
            jumpType = ctr.jumpData.jumpType;
            targetPos = ctr.jumpData.targetPos;
            startPos = heroActor.position;

            commonCurve = GameObject.Instantiate<CommonAnimCurve>(AutoChessFieldViewCtr.Ins.SceneConfig.heroJumpCurve);

            commonCurve.startPos = startPos;
            commonCurve.endPos = targetPos;

            endCall = ctr.jumpData.callEnd;
            animName = jumpType == JumpType.Forward ? AniName.RUSH : AniName.JUMPB;
            animPlayTime = AutoChessFieldViewCtr.Ins.SceneConfig.heroJumpTime;
            var animTime = ctr.heroRenderer.GetAnimationTime(animName);
            if (animTime == 0)//没有动作的话
            {
                animTime = AutoChessFieldViewCtr.Ins.SceneConfig.heroJumpTime;
            }
            else
            {
                animPlayTime = animTime;
            }
            ctr.heroRenderer.PlayAnimation(animName, animTime / animPlayTime);
        }
        public override void Update()
        {
            if (_elapseTime >= animPlayTime)
            {
                if (endCall != null)
                {
                    endCall();
                    endCall = null;
                }
                heroActor.position = targetPos;
                ctr.SwitchState(HeroBehaviourState.Idle);
                return;
            }
            _elapseTime += Time.unscaledDeltaTime;
            heroActor.position = GetPos(_elapseTime / animPlayTime);
        }

        public Vector3 GetPos(float value)
        {
            var pos = commonCurve.EvaluatePosition(value);
            //Debug.LogError(ctr.heroRenderer.heroUnit.ToString()+"  -  " + pos);
            return pos;
        }

        public override void Leave()
        {
            endCall = null;
            ctr.heroRenderer.SetAnimSpeed(1);
            GameObject.Destroy(commonCurve.gameObject);
            commonCurve = null;
        }
    }
}
